
package com.applink.sell_proof;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.applink.sell_proof.api.DataHelper;
import com.applink.sell_proof.api.DataResult;
import com.applink.sell_proof.api.Methods;
import com.applink.sell_proof.builder.TierBuilder;
import com.applink.sell_proof.constant.Constant;
import com.applink.sell_proof.constant.IntentKey;
import com.applink.sell_proof.model.Program;
import com.applink.sell_proof.model.Redeem;
import com.applink.sell_proof.model.Tier;

public class ProgramDetail extends BaseActionBarActivity implements Observer,OnItemClickListener{
	
	private Program mProgram;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.program_detail);
		((ListView)findViewById(android.R.id.list)).setOnItemClickListener(this);
		mProgram = (Program) getIntent().getSerializableExtra(Constant.INTENT_PROGRAM_DETAIL);
		setTitle(mProgram.getName());
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		DataHelper.getInstance().addObserver(this);
		DataHelper.getInstance().getProgramDetail(mProgram.getId());
		showProgressDialog(true);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		DataHelper.getInstance().deleteObserver(this);
	}

	@Override
	public void update(Observable observable, Object data) {
		if(data == null) return;
		DataResult result = (DataResult) data;
		if(result.getMethodName() == Methods.getProgramDetail){
			hideProgressDialog();
			if(result.getErrorCode() == null) {
				if(result.getData() != null){
					List<Tier> tiers = (List<Tier>) result.getData();
					TierBuilder builder = new TierBuilder(this, (ViewGroup) findViewById(android.R.id.list));
					builder.setData(tiers);
				}
			} else {
				// show Error
			}
		}
	}

	@Override
	public void onItemClick(AdapterView<?> listview, View arg1, int position, long arg3) {
		Tier tier = (Tier) listview.getAdapter().getItem(position);
		if(tier.isRedeemable() == false) return;
		Intent intent = new Intent(this, RedeemEdit.class);
		intent.putExtra(IntentKey.ACTIVITY_NAME,  BasePagerActivity.REWARD_ACTIVITY);
		Redeem redeem = new Redeem();
		redeem.setProgramName(mProgram.getName());
		redeem.setCampaignName(mProgram.getCategory());
		redeem.setId(tier.getId());
		redeem.setPoint(tier.getAchivePoint());
		redeem.setProduct(tier.getProduct());
		redeem.setStartdate(tier.getStartDate());
		redeem.setEnddate(tier.getEndDate());
		intent.putExtra(Constant.INTENT_REDEEM_DETAIL, redeem);
		startActivity(intent);
		
	}
	
}
